// 间接更新state的方法对象
import {RECEIVE_ADDRESS, RECEIVE_TYPE, RECEIVE_SHPOS, RECEIVE_USER_INFO, RESET_USER_INFO, RECEIVE_GOODS, RECEIVE_RATINGS, RECEIVE_INFO, INCREMENT_FOOD_COUNT, DECREMENT_FOOD_COUNT} from './mutation-type'
import {reqAddress, reqFoodTypes, reqShops, reqUserInfo, reqLogout, reqShopInfo, reqShopRatings, reqShopGoods} from '../api/index'
export default {
  // 异步获取地址
  // 异步获取地址
  async getAddress ({commit, state}) {
    // 发送异步ajax请求
    const geohash = state.latitude + ',' + state.longitude
    const result = await reqAddress(geohash)
    // 提交一个mutation
    if (result.code === 0) {
      const address = result.data
      commit(RECEIVE_ADDRESS, {address})
    }
  },
  // 异步获取食品分类
  async getTypes ({commit}) {
    // 发送异步请求数据
    const result = await reqFoodTypes()
    // 提交一个mutation
    if (result.code === 0) {
      const types = result.data
      commit(RECEIVE_TYPE, {types})
    }
  },
  // 异步获取商家
  async getShops ({commit, state}) {
    // 发送异步请求数据
    const {longitude, latitude} = state
    const result = await reqShops(longitude, latitude)
    // 提交一个mutation
    if (result.code === 0) {
      const shops = result.data
      commit(RECEIVE_SHPOS, {shops})
    }
  },
  // 同步获取用户信息
  getUsers ({commit}, userInfo) {
    // 发送异步请求数据
    reqUserInfo()
    // 提交一个mutation
    commit(RECEIVE_USER_INFO, {userInfo})
  },
  // 异步获取用户信息
  async getUserInfo ({commit}) {
    const result = await reqUserInfo()
    if (result.code === 0) {
      const userInfo = result.data
      commit(RECEIVE_USER_INFO, {userInfo})
    }
  },
  // 用户异步登出
  async loginOut ({commit}) {
    const result = await reqLogout()
    if (result.code === 0) {
      commit(RESET_USER_INFO)
    }
  },
  // 异步获取商家信息
  async getShopInfo ({commit}) {
    const result = await reqShopInfo()
    if (result.code === 0) {
      const info = result.data
      info.score = 3.5
      commit(RECEIVE_INFO, {info})
    }
  },
  // 异步获取商家评价列表
  async getShopRatings ({commit}) {
    const result = await reqShopRatings()
    if (result.code === 0) {
      const ratings = result.data
      commit(RECEIVE_RATINGS, {ratings})
    }
  },
  // 异步获取商家商品列表
  async getShopGoods ({commit}, callback) {
    const result = await reqShopGoods()
    if (result.code === 0) {
      const goods = result.data
      commit(RECEIVE_GOODS, {goods})
      // 获取到信息后通知组件
      callback && callback()
    }
  },
  // 同步更新food中的count值
  updateFoodCount ({commit}, {isAdd, food}) {
    if (isAdd) {
      commit(INCREMENT_FOOD_COUNT, {food})
    } else {
      commit(DECREMENT_FOOD_COUNT, {food})
    }
  }

}
